<template>
  <div class="wrapper">
    <u-notice-bar v-show="petitionInfo.remark" :text="'備注：' + petitionInfo.remark" speed="80"></u-notice-bar>
    <div class="desc_box" v-if="ossList.length">
      附件下載：
      <a v-for="(item,index) in ossList" :key="index" :href="item.url">{{ item.fileName }}</a>
    </div>
    <!-- PDF 渲染容器 -->
    <PdfPreview ref="pdfPreviewRef" style="margin-top: 30rpx">
      <SignatureOverlay
        v-for="(sig, index) in signatureAreas"
        :key="index"
        :signerInfo.sync="sig"
        mode="signStatus"
        @signatureClick="signatureClick(index, $event)"
      />
    </PdfPreview>
    <SignatureInputDialog
      :visible.sync="dialogVisible"
      :signerInfo="activeSignInfo"
      @save="handleConfirm"
      @closeFun="handleClose"
    />
    <SignatureDate
      :showDate.sync="showDateVisible"
      :signerInfo="activeSignInfo"
      @closeFun="handleClose"
      @save="handleConfirm"
    />
    <view class="btn_group">
      <u-button @click="$goBack()">返回</u-button>
      <u-button v-if="showSignBtn" type="primary" @click="handlePass">完成簽呈</u-button>
      <u-button v-if="showSignBtn" type="warning" @click="handleReject">拒簽</u-button>
    </view>
  </div>
</template>

<script>
import PdfPreview from "@/pages/petition/common/components/PdfPreview.vue";
import SignatureOverlay from "@/pages/petition/common/components/SignatureOverlay.vue";
import SignatureInputDialog from "@/pages/petition/common/components/SignatureInputDialog.vue";
import SignatureDate from "@/pages/petition/common/typeComs/SignatureDate.vue";
import { getPetitionDetail, completeSignOver, rejectPetitionApi } from "@/api/signManage/petition.js";
export default {
  components: {
    PdfPreview,
    SignatureOverlay,
    SignatureInputDialog,
    SignatureDate,
  },
  data() {
    return {
      routeQuery: {},
      petitionInfo: {},
      dialogVisible: false,
      showDateVisible: false,
      activeSignInfo: {},
      activeIndex: -1,
      signatureAreas: [],
      showSignBtn: false
    };
  },
  onLoad(query) {
    this.routeQuery = query;
  },
  computed:{
    ossList() {
      const arr = this.petitionInfo.ossUrl ? this.petitionInfo.ossUrl.split(',') : []
      if (arr.length) {
        return arr.map(url => {
          const fileName = url.substring(url.lastIndexOf('/') + 1)
          return { url, fileName }
        })
      } else {
        return []
      }
    },
  },
  async mounted() {
    try {
      uni.showLoading({
        title: "加載中...",
        mask: true,
      });
      const res = await getPetitionDetail(this.routeQuery);
      const { previewData, petitionInfo } = res.data;
      this.petitionInfo = petitionInfo;
      await this.$refs.pdfPreviewRef.loadDataFromServer(previewData.templateBasicId);
      this.signatureAreas = previewData.boxList.map((item) => {
        const user = item.userList?.[0] || {};
        let fieldValue;
        if (item.boxType === 1 || item.boxType === 5) {
          fieldValue = user.templateSignatureOssUrl;
        } else {
          fieldValue = user.signatureContent;
        }

        return { ...item, fieldValue };
      });
      // 先过滤掉自己能签字的 再判断签字区域中是否存在未完成签署的用户（遍历每个区域下的所有用户）
      this.isHaveNotSign = this.signatureAreas.some(area =>
        // 遍历该区域下所有用户，只要有一个签署状态不是 5，就返回 true
        !area.signatureState
      )
      this.showSignBtn = this.petitionInfo.petitionState === 1 && this.isHaveNotSign
      uni.hideLoading();
    } catch (error) {
      uni.hideLoading();
    }
  },
  methods: {
    signatureClick(index) {
      this.activeSignInfo = this.signatureAreas[index];
      this.activeIndex = index;
      console.log(23232323);
      if (this.activeSignInfo.boxType === 4) {
        // 4这个类型是单选框 单选框是不需要弹窗出现
       return
      }
      if (this.activeSignInfo.boxType === 3) {
        this.showDateVisible = true;
      } else {
        this.dialogVisible = true;
      }
    },
    handleClose() {
      this.showDateVisible = false;
      this.dialogVisible = false;
    },
    handleConfirm(obj) {
      this.signatureAreas[this.activeIndex] = obj;
    },
    handlePass() {
      const requireArr = this.signatureAreas.filter(
        // 过滤掉是必填项以及填写了字段的
        (item) => item.required && !item.fieldValue
      );
      if (requireArr.length) {
        uni.showToast({
          title: "還有必填欄位未填， 請填寫后提交",
          icon: 'none'
        });
        return false;
      }
      const postArr = this.signatureAreas.filter(item => item.signatureState == null).map(item => {
        const obj = {
          templatePetitionUserId: item.templatePetitionUserId,
          boxType: item.boxType,
          petitionId: this.petitionInfo.templatePetitionId,
          templateSignatureId: item.boxType === 1 || item.boxType === 5 ? item.selectImgId : null,
          signatureContent: item.boxType !== 1 && item.boxType !== 5 ? item.fieldValue : null
        }
        return obj
      })
      completeSignOver({ list: postArr }).then((res) => {
          uni.$emit('showMessage', {
            title: res.message,
            icon: 'success',
          })
          uni.redirectTo({url: '/pages/petition/myPetition/index'})
        }).catch(() => {
        });
    },
    handleReject() {
      this.showRejectModal();
    },
    // 封装一个可重复调用的方法
    async showRejectModal() {
      uni.showModal({
        title: "拒簽原因",
        editable: true,
        placeholderText: "请填寫拒簽原因...",
        success: async (res) => {
          if (res.confirm) {
            const reason = res.content?.trim();
            if (!reason) {
              uni.showToast({ title: "請填寫拒簽原因", icon: "none" });
              // 递归重新弹出
              setTimeout(() => {
                this.showRejectModal();
              }, 50);
              return;
            }

            // 正常处理
            try {
              const payload = {
                deniedContent: reason,
                petitionId: this.petitionInfo.templatePetitionId,
              };
              const apiRes = await rejectPetitionApi(payload);
              uni.showToast({ title: apiRes.message || "提交成功" });
              // 跳转
              setTimeout(() => {
                uni.redirectTo({ url: "/pages/dashboard/index" });
              }, 1000);
            } catch (error) {
              uni.showToast({ title: "提交失败", icon: "none" });
            } finally {
            }
          }
        },
      });
    },
  },
};
</script>

<style scoped lang="scss">
.wrapper {
  padding: 30rpx;
  /* padding-bottom: 0; */
  background-color: #f5f6fa;
  min-height: 100vh;
  display: flex;
  flex-direction: column;

  // 附件區塊
  .desc_box {
    margin: 20rpx 0;
    padding: 20rpx;
    border-radius: 12rpx;
    background: #fff;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
    font-size: 28rpx;
    color: #444;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 16rpx;

    a {
      color: #2d8cf0;
      text-decoration: underline;
      font-weight: 500;
      word-break: break-all;
      transition: all 0.2s;

      &:hover {
        color: #1765ad;
      }
    }
  }

  // PDF 區域
  ::v-deep .pdf-preview-container {
    margin: 30rpx auto;
    border-radius: 12rpx;
    overflow: hidden;
    box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.08);
    background: #fff;
  }

  // 按鈕組
  .btn_group {
    margin-top: auto;
    padding: 40rpx 20rpx 120rpx;
    background: #fff;
    border-top: 1px solid #eee;
    display: flex;
    justify-content: space-around;
    gap: 30rpx;
    position: sticky;
    bottom: 0;
    z-index: 9;

    .u-button {
      flex: 1;
      max-width: 240rpx;
      font-size: 30rpx;
      font-weight: bold;
      border-radius: 12rpx;
      height: 88rpx;
      line-height: 88rpx;
      box-shadow: 0 6rpx 12rpx rgba(0, 0, 0, 0.08);
      transition: transform 0.2s;

      &:active {
        transform: scale(0.96);
      }
    }

    // 顏色細化
    .u-button--primary {
      background-color: #2d8cf0 !important;
    }

    .u-button--warning {
      background-color: #f56c6c !important;
      border-color: #f56c6c !important;
    }
  }
}
</style>